package com.smt.common.aspect;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.enums.StageEnum;
import com.smt.common.utils.BillUtils;
import com.smt.common.utils.Constant;
import com.smt.modules.app.annotation.BillAndGrade;
import com.smt.modules.bus.entity.BillEntity;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.entity.ProjectTaskEntity;
import com.smt.modules.bus.service.BillService;
import com.smt.modules.bus.service.ProjectTaskService;
import com.smt.modules.bus.vo.CompanyVo;
import com.smt.modules.bus.vo.ProjectTaskVo;
import com.smt.modules.bus.vo.ProjectVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangyi
 * @date 2018/10/31 16:21
 */
@Component
@Aspect
@Slf4j
public class BillAndGradeAspect {

    @Autowired
    private BillService billService;
    @Autowired
    private BillUtils billUtils;
    @Autowired
    private ProjectTaskService projectTaskService;

    @Pointcut("@annotation(com.smt.modules.app.annotation.BillAndGrade)")
    public void billAndGrade() {
    }

    /**
     * 增强方法
     *
     * @param joinPoint
     */
    @After(value = "billAndGrade()")
    public void billAndGradeOperate(JoinPoint joinPoint) {
        //判断操作类型
        String operate = getOperate(joinPoint);
        synchronized (this) {
            //主线任务只完成一次，操作完写入账单增加积分
            Object[] args = joinPoint.getArgs();
            List<Object> objects = Arrays.asList(args);
            if (Constant.TASK_1.equals(operate)) {
                task1(objects);
            } else if (Constant.TASK_2.equals(operate)) {
                task2(objects);
            } else if (Constant.TASK_3.equals(operate)) {
                task3(objects);
            } else if (Constant.TASK_4.equals(operate)) {
                task4(objects);
            } else if (Constant.TASK_5.equals(operate)) {
                task5(objects);
            } else if (Constant.TASK_6.equals(operate)) {
                task6(objects);
            } else if (Constant.TASK_7.equals(operate)) {
                task7(objects);
            }
        }
    }

    /**
     * 获取操作类型
     *
     * @param joinPoint
     * @return
     */
    private String getOperate(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        BillAndGrade annotation = method.getAnnotation(BillAndGrade.class);
        String value = annotation.value();
        return value;
    }

    /**
     * 完成一个标杆任务
     *
     * @return
     */
    private boolean task1(List<Object> objects) {
        return isBill(objects, Constant.TASK_1);
    }

    /**
     * 完成生命周期的所有标杆任务
     *
     * @return
     */
    private boolean task2(List<Object> objects) {
        return isBill(objects, Constant.TASK_2);
    }

    /**
     * 编写公司简介，增加大家对公司的了解
     *
     * @return
     */
    private boolean task3(List<Object> objects) {
        return isBill(objects, Constant.TASK_3);
    }

    /**
     * 创建一个项目，让企业有的放矢
     *
     * @return
     */
    private boolean task4(List<Object> objects) {
        return isBill(objects, Constant.TASK_4);
    }

    /**
     * 上传公司的营业执照，保障企业的合法性
     *
     * @return
     */
    private boolean task5(List<Object> objects) {
        return isBill(objects, Constant.TASK_5);
    }

    /**
     * 创建一家公司
     *
     * @return
     */
    private boolean task6(List<Object> objects) {
        return isBill(objects, Constant.TASK_6);
    }

    /**
     * 邀请一位成员
     *
     * @return
     */
    private boolean task7(List<Object> objects) {
        return isBill(objects, Constant.TASK_7);
    }

    /**
     * 查找用户账单操作
     *
     * @param objs  输入参数列表
     * @param title 账单标题
     * @return
     */
    private boolean isBill(List<Object> objs, String title) {
        MemberUserEntity localMember = null;
        for (Object o : objs) {
            if (o instanceof MemberUserEntity) {
                localMember = (MemberUserEntity) o;
                break;
            }
        }
        if (localMember == null) {
            //当前用户不存在
            return false;
        } else {
            BillEntity billEntity = null;
            //公司简介和修改公司营业执照混合在一起了，首先进入的应该是修改公司简介，此时需要一个标志位让修改公司营业执照这个动作也能单独进入其方法体里面
            boolean flag = false;
            EntityWrapper<BillEntity> billEntityEntityWrapper = new EntityWrapper<>();
            billEntityEntityWrapper.eq("type", 1)
                    .eq("expenditure", 1)
                    .eq("is_reward", 0)
                    .eq("bus_business_id", localMember.getUserId());
            //获取到当前用户完成账单数量
            if (title.equals(Constant.TASK_3)) {
                BillEntity billEntity1 = billService.selectOne(new EntityWrapper<BillEntity>()
                        .eq("type", 1)
                        .eq("expenditure", 1)
                        .eq("is_reward", 0)
                        .eq("bus_business_id", localMember.getUserId())
                        .eq("bill_title", Constant.TASK_3));
                if (Objects.isNull(billEntity1)) {
                    billEntityEntityWrapper.eq("bill_title", Constant.TASK_5);
                    billEntity = billService.selectOne(billEntityEntityWrapper);
                    flag = true;
                    return addBillAndGradeOp(billEntity, objs, title, localMember, flag);
                }
                return addBillAndGradeOp(billEntity1, objs, title, localMember, flag);
            } else {
                billEntityEntityWrapper.eq("bill_title", title);
                billEntity = billService.selectOne(billEntityEntityWrapper);
            }
            return addBillAndGradeOp(billEntity, objs, title, localMember, flag);
        }

    }

    /**
     * 增加账单操作
     *
     * @param args
     * @param desc
     */
    private boolean addBillAndGradeOp(BillEntity billEntity, List<Object> args,
                                      String desc, MemberUserEntity memberUserEntity,
                                      boolean flag) {
        //此时的账单是待领取状态，无需修改
        if (Objects.isNull(billEntity)) {
            log.info("该用户已经完成该主线任务：{}", desc);
            return false;
        }
        //公司信息
        CompanyVo company = null;
        //任务信息
        ProjectTaskVo projectTaskVo = null;
        //项目信息
        ProjectVo projectVo = null;
        for (Object o : args) {
            if (o instanceof CompanyVo) {
                company = (CompanyVo) o;
                break;
            } else if (o instanceof ProjectTaskVo) {
                projectTaskVo = (ProjectTaskVo) o;
                break;
            } else if (o instanceof ProjectVo) {
                projectVo = (ProjectVo) o;
            }
        }
        //新建公司
        if (desc.equals(Constant.TASK_6)) {
            //加入奖励信息
            boolean b = billUtils.addBills(billEntity, memberUserEntity, Constant.COMPANY_CREATE);
            log.info("新建公司成功：{}，奖励发放状态：{}", billEntity.toString(), b);
        } else if (desc.equals(Constant.TASK_3) || flag) {
            //编写公司简介，增加大家对公司的了解
            if (memberUserEntity.getUserId().equals(company.getMemberId())) {
                boolean b;
                if (Objects.isNull(company.getBrief())) {
                    b = false;
                    log.info("公司简历未填写");
                } else {
                    b = billUtils.addBills(billEntity, memberUserEntity, Constant.COMPANY_INTRODUCTION);
                }
                log.info("编写公司简介，增加大家对公司的了解：{} 奖励发放状态：{}", billEntity, b);
                boolean b1;
                if (Objects.isNull(company.getImageBusinessLicense())) {
                    b1 = false;
                    log.info("营业执照未上传");
                } else {
                    billEntity.setBillTitle(Constant.TASK_5);
                    b1 = billUtils.addBills(billEntity, memberUserEntity, Constant.COMPANY_BUSINESS);
                }
                log.info("上传公司的营业执照，保障企业的合法性：{} 奖励发放状态：{}", billEntity, b1);
            } else {
                log.info("当前用户不是公司创建者：当前用户id{},创建者id:{}", memberUserEntity.getUserId(), company.getMemberId());
            }
        } else if (desc.equals(Constant.TASK_5)) {
            //同上公司简介
        } else if (desc.equals(Constant.TASK_1)) {
            //完成一个任务
            if (Objects.isNull(projectTaskVo)) {
                log.info("项目信息为空！");
            }
            //当前用户修改任务的状态  50提交审批
            Integer status = projectTaskVo.getStatus();
            log.info("当用户修改任务状态时候为50时候，在用户角度算是完成，此时用户操作的任务状态{}", status);
            if (status != null && status.equals(50)) {
                boolean b = billUtils.addBills(billEntity, memberUserEntity, null);
                log.info("任务提交审批 ,奖励方法状态{}", b);
                return true;
            } else {
                log.info("任务状态修改状态{}", status);
            }
        } else if (desc.equals(Constant.TASK_2)) {
            //完成发布量产的所有标杆任务
            Long projectId = null;
            Integer stageId = null;
            for (Object o : args) {
                if (o.getClass().equals(Long.class)) {
                    //项目id
                    projectId = new Long((Long) o);
                } else if (o.getClass().equals(Integer.class)) {
                    //阶段id
                    stageId = new Integer((Integer) o);
                }
            }
            boolean result = true;
            //根据业务需求，此时阶段定位到生命周期中
            if (stageId.equals(StageEnum.LIFE_STAGE.key())) {
                List<ProjectTaskEntity> projectTaskEntityList = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                        .eq("project_id", projectId)
                        .eq("stage_id", stageId)
                        .in("status", Constant.SQL_CON));
                for (ProjectTaskEntity p : projectTaskEntityList) {
                    //当前任务的状态
                    Integer status = p.getStatus();
                    //去除删除标记状态
                    if (status.equals(3)) {
                        continue;
                    }
                    //1:完成状态 50 提交审批状态
                    if (!status.equals(1) && !status.equals(50)) {
                        result = false;
                        break;
                    }
                }
                //完成生命周期所有任务
                if (result) {
                    boolean b = billUtils.addBills(billEntity, memberUserEntity, null);
                    log.info("完成生命周期所有任务 ,奖励方法状态{}", b);
                    return true;
                } else {
                    log.info("未完成生命周期内的所有任务");
                }
            }
        } else if (desc.equals(Constant.TASK_4)) {
            //创建一个项目
            boolean b = billUtils.addBills(billEntity, memberUserEntity, null);
            if (b) {
                log.info("创建一个项目 ,项目信息 {}", projectVo);
                return true;
            } else {
                log.info("创建项目失败");
            }
        } else if (desc.equals(Constant.TASK_7)) {
            //邀请一位成员
            boolean b = billUtils.addBills(billEntity, memberUserEntity, null);
            if (b) {
                log.info("邀请一位成员 参数信息{}", args);
                return true;
            } else {
                log.info("邀请成员失败");
            }
        }
        return false;
    }
}
